import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/publishReplay';
import { HttpUtils } from '../utils/http-utils';

@Injectable()
export class UntreatedMessagesNumberService {

  number: Subject<number> = new BehaviorSubject<number>(0);

  constructor(private http: Http) { }

  getNumber () :Observable<number> {
    let observable = this.http.get('api/messages/untreated-number')
      .publishReplay(1)
      .refCount()
      .map(HttpUtils.extractData)
        .map((data) => {return data.total})
      .catch(HttpUtils.handleError)
    ;

    observable.subscribe(number => this.number.next(number));

    return observable;
  }

}
